<template>
  <div class="main">
    <div class="nav">
      <van-nav-bar>
        <template #right>
          <van-popover
            v-model:show="showPopover"
            :actions="actions"
            @select="onSelect"
            theme="dark"
            placement="bottom-end"
          >
            <template #reference>
              <van-icon name="add-o" color="#333" />
            </template>
          </van-popover>
        </template>
      </van-nav-bar>
    </div>
    <div class="loading" v-if="showLoading">
      <van-loading type="spinner" />
    </div>
    <div class="search">
      <input type="text" placeholder="搜索" v-model="searchText" />
      <van-icon name="search" v-if="searchText === ''" />
    </div>
    <div class="chatList">
      <div
        class="chatItem"
        @click="goChatRoom(item)"
        v-for="(item, index) in chatList.chatList"
        :key="item.chatId"
      >
        <div class="left">
          <van-badge :content="item.unReadCount === 0 ? '' : item.unReadCount">
            <img
              v-if="item.from.name !== userInfo.userName"
              :src="item.from.avatar"
              alt=""
            />
            <img v-else :src="item.to.avatar" alt="" />
          </van-badge>
          <div>
            <div v-if="item.from.name !== userInfo.userName">
              {{ item.from.name }}
            </div>
            <div v-else>{{ item.to.name }}</div>
            <div v-if="item">
              <div
                v-if="
                  item.type === 'image/png' ||
                  item.type === 'image/jpeg' ||
                  item.type === 'image/gif' ||
                  item.type === 'image/jpg' ||
                  item.type === 'image/svg+xml' ||
                  item.type === 'image/webp' ||
                  item.type === 'image/apng' ||
                  item.type === 'image/avif' ||
                  item.type === 'image/bmp'
                "
              >
                {{
                  item.from.name !== userInfo.userName
                    ? item.from.name
                    : item.to.name
                }}:图片
              </div>
              <div v-else>
                {{
                  item.from.name !== userInfo.userName
                    ? item.from.name
                    : item.to.name
                }}:{{ item.msg }}
              </div>
            </div>
          </div>
        </div>
        <div class="right" v-if="item.timeStamp">
          {{ timeFormat(item.timeStamp) }}
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, getCurrentInstance, onMounted } from "vue";
import { showToast } from "vant";
import { useRouter } from "vue-router";
import indexedDBStore from "@/store/module/indexedDB";
import addressBookStore from "@/store/module/addressBook";
import { addData, queryIndexDBAll } from "@/utils/utils";
import { sendNotification } from "@/utils/notification.ts";
import chatListStore from "@/store/module/chatList";
import { timeFormat } from "@/utils/utils";

let db = indexedDBStore();
let chatList = chatListStore();
let addressBook = addressBookStore();
onMounted(() => {
  if (chatList.chatList.length === 0) {
    setTimeout(() => {
      queryIndexDBAll({
        db: db.indexedDB,
        tableName: "chatList",
        queryIndex: "belongToId",
        queryIndexValue: userInfo.uid,
      }).then((res) => {
        let chatListData = res.map((item) => {
          return {
            chatId: item.chatId,
            from: {
              name: userInfo.userName,
              avatar: userInfo.userAvatar,
              id: userInfo.uid,
            },
            to: {
              name: item.chatName,
              avatar: item.chatAvatar,
              id: item.toId,
            },
            msg: "",
            type: "notice",
            timeStamp: "",
          };
        });
        chatListData.forEach((item) => {
          chatList.addChat(item);
        });
      });
    }, 100);
  }
  showLoading.value = true;
  setTimeout(() => {
    showLoading.value = false;
  }, 1000);
});
const router = useRouter();
let global = getCurrentInstance()?.appContext.config.globalProperties.$global;
const userInfo = JSON.parse(localStorage.getItem("userInfo"));
const showLoading = ref(false);
global.ws.onmessage = (e) => {
  let data = JSON.parse(e.data);
  console.log("onmessage", data);
  if (data.type === "notice") {
    if (data.msgType === "friendRequest") {
      addressBook.addUnReadCount(data.data);
      addressBook.updateAddFriendList(data.data);
    }
  } else {
    if (data.type === "message" && data.from.id !== userInfo.uid) {
      sendNotification(`${data.from.name}：${data.msg}`, data.from.avatar);
    } else if (data.url && data.from.id !== userInfo.uid) {
      sendNotification(`${data.from.name}：图片`, data.from.avatar);
    }
    db.unReadCount++;
    localStorage.setItem("unReadCount", String(db.unReadCount));
    chatList.addChat(data);
    addData(db.indexedDB, "messages", data);
  }
};
const showPopover = ref(false);
const searchText = ref("");
// 通过 actions 属性来定义菜单选项
const actions = [
  { text: "发起群聊", index: 0 },
  { text: "添加朋友", index: 1 },
];
const onSelect = (action: { index }) => {
  if (action.index === 1) {
    router.push("/addFriend");
  }
};
const goChatRoom = (e) => {
  router.push({
    path: "/chatRoom",
    state: {
      chatItem: JSON.parse(JSON.stringify(e)),
    },
  });
};
</script>

<style scoped lang="scss">
.main {
  box-sizing: border-box;
  background-color: #ebe8e7;
  min-height: 100vh;
}

.loading {
  text-align: center;
  background-color: #fff;
  height: 30px;
}

.chatList {
  margin: 20px 15px;

  .chatItem {
    border: 1px solid #ddd;
    display: flex;
    justify-content: space-between;
    padding: 5px 10px;

    .right {
      font-size: 14px;
      color: #a8a8a8;
    }

    .left {
      display: flex;

      & > div:nth-child(2) {
        & > div:first-child {
          font-weight: bold;
          font-size: 15px;
          margin-bottom: 2px;
        }

        & > div:nth-child(2) {
          font-size: 14px;
          color: #a8a8a8;
          max-width: 150px;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        }
      }

      img {
        width: 30px;
        height: 30px;
        border-radius: 5px;
        object-fit: cover;
        margin-right: 5px;
      }
    }
  }
}

.nav {
  .van-icon {
    font-size: 20px;
  }
}

.search {
  margin: 10px 0;
  text-align: center;
  width: 100vw;
  position: relative;

  .van-icon {
    position: absolute;
    top: 3px;
    left: 158px;
    color: #ccc;
    font-size: 18px;
  }

  input {
    padding: 3px;
    width: 95vw;
    text-align: center;
    font-size: 14px;
    border: 0;
    border: 1px solid #ddd;
  }

  input::placeholder {
    color: #ccc;
  }
}
</style>
